import { AliSMSService } from './../service/alismsService';
import * as Koa from 'koa';
import { route, RouteOptionsVerify, RouteOptionsBase } from '../common/http';
import * as Jimp from 'jimp';
import { ServiceManager } from '../common/serviceFactory/serviceManager';
import { AuthenService } from '../service/authenService';
import { AliOSS } from '../service/aliossService';
import * as fs from 'fs';
import * as path from 'path';
import { Guid } from '../common';
import xlsx from 'node-xlsx';
// let pcaCode = require('china-division/dist/pca-code.json');

const authSvr = ServiceManager.Current.GetService<AuthenService>('AuthenService');
const aliOSS = ServiceManager.Current.GetService<AliOSS>('AliOSS');
// const tenSvr = ServiceManager.Current.GetService<TenPayService>('TenPayService');
const aliSMS = ServiceManager.Current.GetService<AliSMSService>('AliSMSService');

const JimpImageWrite = async (image: Jimp, filtPath: string) => {
    return new Promise((resolve, reject) => {
        image.write(filtPath, (err, image) => {
            if (err) {
                reject(err);
            }
            else {
                resolve(image);
            }
        })
    })
}

class RescoureController {
    @route(new RouteOptionsVerify('POST', '/api/rescoure/file'))
    async uploadFile(ctx: Koa.Context, next) {
        let orgId = ctx.header['orgid'];
        let { mode, ossDir, selfFileName } = ctx.query;
        let DirName = 'imageStore';

        const file = ctx.request.files.file;
        const reader = fs.createReadStream(file.path);
        let round = Guid.GetGuid();
        DirName += "/" + orgId;
        let saveDirName = 'public/' + DirName;

        let hasDir = fs.existsSync(saveDirName);
        if (!hasDir) {
            fs.mkdirSync(saveDirName);
        }

        let fObj = getFileSuffix(file.name);

        let fileSuffix = fObj.fileSuffix;
        let fileName = `${fObj.fileName}_${round}.${fileSuffix}`;
        let filePath = path.join(__dirname, '../../' + saveDirName + '/') + fileName;
        // 创建可写流
        const upStream = fs.createWriteStream(filePath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);

        await saveStreamEnd(upStream);

        let result: any = {};
        if (mode == 'wechat') {
            // 微信支付进件
            // let r: any = await tenSvr.UploadMedia(filePath, file.name);
            // result.wechat = r;
            // let url = await aliOSS.put(`wechatMedia/${storeId}/${r.media_id}.${getFileSuffix(file.name)}`, filePath);
            // fs.unlink(filePath, () => { });
            // result.fileUrl = url;
        }
        else {
            if (ossDir) {
                ossDir = ossDir + '/';
            }
            else {
                ossDir = '';
            }

            let fn = `${ossDir}${fileName}`;
            if (selfFileName) {
                fn = selfFileName;
            }

            let url = await aliOSS.put(`fileStore/${orgId}/${fn}`, filePath);
            fs.unlink(filePath, () => { });

            // let url = `imageStore/${orgId}/${round}.${getFileSuffix(file.name)}`;
            // let url = DirName + '/' + fileName;
            result.fileUrl = url;
        }

        ctx.response.body = result;

        await next();
    }

    @route(new RouteOptionsVerify('GET', '/api/rescoure/file'))
    async queryFiles(ctx: Koa.Context, next) {
        let params: {
            orgId: string;
            dir: string;
        } = ctx.query;

        if (params.dir) {
            params.dir = '/' + params.dir + '/';
        }

        ctx.response.body = await aliOSS.listDir(`fileStore/${params.orgId}${params.dir}`);
        await next();
    }

    @route(new RouteOptionsVerify('delete', '/api/rescoure/file'))
    async deleteOssFile(ctx: Koa.Context, next) {
        let { fileName, orgId, completeFname } = ctx.query;

        let fn = `fileStore/${orgId}/${fileName}`;
        if (completeFname) {
            fn = completeFname;
        }

        ctx.response.body = await aliOSS.deleteFile(fn);
        await next();
    }

    @route(new RouteOptionsBase('get', '/api/industry'))
    async getIndustryConfig(ctx: Koa.Context, next) {
        let result = [
            {
                industry: 'coffee',
                value: '咖啡/奶茶'
            },
            {
                industry: 'hotPot',
                value: '火锅'
            },
            {
                industry: 'westernStyleFood',
                value: '西餐'
            },
            {
                industry: 'chineseFood',
                value: '中餐'
            },
            {
                industry: 'fastFood',
                value: '通用快餐'
            }
        ];

        ctx.response.body = result;

        await next();
    }

    @route(new RouteOptionsVerify('POST', '/api/ali/sms/code/send'))
    async sendVerifyCodeSMS(ctx: Koa.Context, next) {
        let { phone } = ctx.query;
        ctx.response.body = await aliSMS.SendVerifyCodeSMS(phone);
        await next();
    }

    @route(new RouteOptionsBase('POST', '/api/rescoure/export/excel'))
    async exportExcel(ctx: Koa.Context, next) {
        let data: [][] = ctx.request.body;

        let buffer: Buffer = xlsx.build([{ name: 'sheet1', data }]);

        ctx.set('Content-type', 'application/vnd.openxmlformats');
        ctx.set('Content-disposition', 'attachment;filename=dataValues.xlsx');

        ctx.response.body = buffer;

        await next();
    }

    // @route(new RouteOptionsBase('GET', '/api/rescoure/china'))
    // async getChineseDivisions(ctx: Koa.Context, next) {
    //     ctx.response.body = pcaCode;
    //     await next();
    // }

    // @route(new RouteOptionsVerify('GET', '/api/ali/sms/code/verify'))
    // async test(ctx: Koa.Context, next) {
    //     let { code, phone } = ctx.query;
    //     ctx.response.body = await aliSMS.VerifcationCode(phone, code);
    //     await next();
    // }
}

const saveStreamEnd = async (upStream) => {
    return new Promise((resovle, reject) => {
        upStream.on('finish', async () => {
            resovle(null);
        });
    });
}

const getFileSuffix = (fileName: string) => {
    var index = fileName.lastIndexOf(".");
    var suffix = fileName.substr(index+1);

    let result = {
        fileName: '',
        fileSuffix: ''
    }
    if (index && index> -1) {
        result.fileName = fileName.substr(0,index);
        result.fileSuffix = suffix;
    }
    return result;
}